package foo.bar.wiki.services;

import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.orm.jpa.JpaCallback;
import foo.bar.wiki.domain.User;
import foo.bar.wiki.domain.Space;
import foo.bar.wiki.domain.Page;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class DomainObjectAspect2Service extends AbstractJpaAwareService {

    DomainObjectAspect2Service(){}

    public DomainObjectAspect2Service(JpaTemplate jpaTemplate) {
        super(jpaTemplate);
    }

    public User getUserById(final String userId) {
        return (User) getJpaTemplate().execute(new JpaCallback() {
            public Object doInJpa(EntityManager em) throws PersistenceException {
                Query q = em.createNamedQuery("User_findByUserId");
                q.setParameter("userId", userId);
                return getFirstResult(q);
            }
        });
    }

    public Space getSpaceById(final String spaceId) {
        return (Space) getJpaTemplate().execute(new JpaCallback() {
            public Object doInJpa(EntityManager em) throws PersistenceException {
                Query q = em.createNamedQuery("Space_findSpaceById");
                q.setParameter("spaceId", spaceId);
                return getFirstResult(q);
            }
        });
    }

    public Page getPageById(final String pageId) {
        return (Page) getJpaTemplate().execute(new JpaCallback() {
            public Object doInJpa(EntityManager em) throws PersistenceException {
                Query q = em.createNamedQuery("Page_findPageById");
                q.setParameter("pageId", pageId);
                return getFirstResult(q);
            }
        });
    }
}
